package com.xm_jd.tags;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.xm_jd.model.entitys.Pages;

/**
 * @author lenovo
 *	��ҳ��Tag
 */
public class PageTag extends SimpleTagSupport{
	private String url;//����·��
	private Pages<?> pages;//ҳ��
	
	@Override
	public void doTag() throws JspException, IOException {
		super.doTag();
		//�������ҳ��  ��һҳ 123456 ��һҳ
		StringBuffer sb = new StringBuffer();
		//��õ�ǰҳ��
		int currentpage = pages.getCurrentpage();
		//��һҳ
		if(currentpage==1){
			sb.append("<a><上一页</a>");
		}else{
			sb.append("<a href='"+url+"?currentpage="+(currentpage-1)+"'><上一页</a>");
		}
		//ѭ��ҳ��
		for (int i = 1; i <= pages.getPages(); i++) {
			if(currentpage==i){
				sb.append("<a class='hhhh' href='"+url+"?currentpage="+i+"'>"+i+"</a>");
			}else{
				sb.append("<a class='hhhh1' href='"+url+"?currentpage="+i+"'>"+i+"</a>");
			}
		}
		//��һҳ
		if(currentpage==pages.getPages()){
			sb.append("<a>下一页></a>");
		}else{
			sb.append("<a href='"+url+"?currentpage="+(currentpage+1)+"'>下一页></a>");
		}
		//��ƴ�Ӻõ��ַ���д��ҳ��
		this.getJspContext().getOut().print(sb);
	}
	
	public String getParamStr() throws UnsupportedEncodingException {
		PageContext pageContext = (PageContext) this.getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		Enumeration<String> pnames = request.getParameterNames();

		List<String> params = new ArrayList<>();

		while (pnames.hasMoreElements()) {
			String name = (String) pnames.nextElement();
			//������ǵ�ǰҳ������������ͽ��д���
			if (!"currentpage".equalsIgnoreCase(name)) {
				String[] values = request.getParameterValues(name);
				for (String value : values) {
					if (value!=null && !"".equals(value)) {
						params.add(name + "=" + URLEncoder.encode(value, "UTF-8"));
					}
				}
			}
		}

		StringBuffer sb = new StringBuffer();
		if (params.size() > 0) {
			sb.append("&");
			for (String item : params) {
				sb.append(item).append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
		}

		return sb.toString();
	}

		public String getUrl() {
			return url;
		}
	
		public void setUrl(String url) {
			this.url = url;
		}
	
		public Pages<?> getPages() {
			return pages;
		}
	
		public void setPages(Pages<?> pages) {
			this.pages = pages;
		}
	
}
